package com.example.time_planner.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.time_planner.R;
import com.example.time_planner.dataBase.Task;
import com.example.time_planner.dataBase.TaskHelper;

public class CreateTaskActivity extends ListActivity {

	private static final String TASK_CREATED = "Task is successfully created !";
	private static final String TASK_NOT_CREATED = "Task is not created fill all information !";

	private CheckBox checkBoxAlarm;
	private CheckBox checkBoxOnTop;
	private Button saveTaskButton;
	private Button setDateButton;
	private Button setTimeStartButton;
	private Button setTimeEndButton;
	private Button setAlarmButton;
	private TextView alarmTimeText;
	private EditText addTaskName;
	private EditText addTaskDescription;
	private Spinner categorySpinner;
	private String startEve;
	private String endEve;
	private Calendar alarmCalendar = Calendar.getInstance();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_task_activity);
		setIdForViews();
		settingTheCatsInSpinner();
		// Button click Listener
		addListenerOnButtons();
		setTimeEndButton.setEnabled(false);
		setTimeStartButton.setEnabled(false);

	}

	private String calculatingDurationOfEvents(String start, String end) {

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
		Date date1 = null;
		Date date2 = null;

		try {
			date1 = simpleDateFormat.parse(start);
			date2 = simpleDateFormat.parse(end);
		} catch (ParseException e) {
			Log.i("CONVERT", "Cant convert DURATION");
			e.printStackTrace();
		}

		long diff = date2.getTime() - date1.getTime();
		long diffHours = diff / (60 * 60 * 1000) % 24;

		return String.valueOf(diffHours);
	}

	private void settingTheCatsInSpinner() {
		String[] categories = getResources().getStringArray(
				R.array.categories_for_spinner);
		// categorySpinner = (Spinner) findViewById(R.id.category_spinner);
		List<String> categoryList = new ArrayList<String>();
		for (String cat : categories) {
			categoryList.add(cat);
		}

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, categoryList);

		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		categorySpinner.setAdapter(dataAdapter);
	}

	private void setIdForViews() {
		checkBoxAlarm = (CheckBox) findViewById(R.id.check_box_alarm);
		checkBoxOnTop = (CheckBox) findViewById(R.id.check_box_on_top);
		setTimeStartButton = (Button) findViewById(R.id.set_time_button);
		setDateButton = (Button) findViewById(R.id.set_date_button);
		saveTaskButton = (Button) findViewById(R.id.saveTaskButton);
		addTaskName = (EditText) findViewById(R.id.task_name);
		addTaskDescription = (EditText) findViewById(R.id.task_description);
		categorySpinner = (Spinner) findViewById(R.id.category_spinner);
		setTimeEndButton = (Button) findViewById(R.id.set_time_end_button);
		setAlarmButton = (Button) findViewById(R.id.setAlarmTime);
		alarmTimeText = (TextView) findViewById(R.id.alarmTimeText);

	}

	// Add spinner data

	public void addListenerOnButtons() {
		setDateButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final Calendar c = Calendar.getInstance();
				int mYear = c.get(Calendar.YEAR);
				int mMonth = c.get(Calendar.MONTH);
				int mDay = c.get(Calendar.DAY_OF_MONTH);
				// categorySpinner = (Spinner)
				// findViewById(R.id.category_spinner)

				DatePickerDialog dpd = new DatePickerDialog(
						CreateTaskActivity.this,
						new DatePickerDialog.OnDateSetListener() {

							@Override
							public void onDateSet(DatePicker view, int year,
									int monthOfYear, int dayOfMonth) {
								setDateButton.setText(dayOfMonth + "/"
										+ monthOfYear + "/" + year);
							}
						}, mYear, mMonth, mDay);
				dpd.show();
				alarmCalendar.set(mYear, mMonth, mDay);
				setTimeStartButton.setEnabled(true);
			}
		});

		setTimeStartButton.setOnClickListener(new OnClickListener() {
			Calendar mCalendar = Calendar.getInstance();
			SimpleDateFormat mSDF = new SimpleDateFormat("HH:mm");

			@Override
			public void onClick(View v) {
				Time time = new Time();
				int mHour = time.hour;
				int mMinute = time.minute;
				TimePickerDialog tpd = new TimePickerDialog(
						CreateTaskActivity.this,
						new TimePickerDialog.OnTimeSetListener() {

							@Override
							public void onTimeSet(TimePicker view,
									int hourOfDay, int minute) {
								mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
								mCalendar.set(Calendar.MINUTE, minute);
								String time = mSDF.format(mCalendar.getTime());
								setTimeStartButton.setText(time);
								startEve = time;
							}
						}, mHour, mMinute, true);
				tpd.show();
				setTimeEndButton.setEnabled(true);
			}
		});

		setTimeEndButton.setOnClickListener(new OnClickListener() {
			Calendar mCalendar = Calendar.getInstance();
			SimpleDateFormat mSDF = new SimpleDateFormat("HH:mm");

			@Override
			public void onClick(View v) {
				Time time = new Time();
				int mHour = time.hour;
				int mMinute = time.minute;
				TimePickerDialog tpd = new TimePickerDialog(
						CreateTaskActivity.this,
						new TimePickerDialog.OnTimeSetListener() {
							@Override
							public void onTimeSet(TimePicker view,
									int hourOfDay, int minute) {
								mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
								mCalendar.set(Calendar.MINUTE, minute);
								String time = mSDF.format(mCalendar.getTime());
								setTimeEndButton.setText(time);
								endEve = time;
							}
						}, mHour, mMinute, true);
				tpd.show();
			}
		});

		checkBoxAlarm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (checkBoxAlarm.isChecked()) {
					setAlarmButton.setVisibility(View.VISIBLE);
					alarmTimeText.setVisibility(View.VISIBLE);

					setAlarmButton.setOnClickListener(new OnClickListener() {
//						alarmCalendar = Calendar.getInstance();
						SimpleDateFormat aSDF = new SimpleDateFormat("HH:mm");
						
						@Override
						public void onClick(View v) {
							Time aTime = new Time();
							int aHour = aTime.hour;
							int aMinute = aTime.minute;
							TimePickerDialog tpd = new TimePickerDialog(
									CreateTaskActivity.this,
									new TimePickerDialog.OnTimeSetListener() {
										@Override
										public void onTimeSet(TimePicker view,
												int hourOfDay, int minute) {
											alarmCalendar.set(Calendar.HOUR_OF_DAY,	hourOfDay);
											alarmCalendar.set(Calendar.MINUTE, minute);
											String time = aSDF.format(alarmCalendar.getTime());
											alarmTimeText.setText(time);
											
											
										}
									}, aHour, aMinute, true);
							tpd.show();
							
						}
					});

				} else {
					setAlarmButton.setVisibility(View.INVISIBLE);
					alarmTimeText.setVisibility(View.INVISIBLE);
				}

			}
		});

		saveTaskButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				addingTaskToDataBase();
				addAlarm(alarmCalendar,addTaskName.getText().toString(), addTaskDescription.getText().toString());
				finish();
			}
		});
	}

	private void addAlarm(Calendar c, String taskName, String taskDescription) {
		Calendar cal = alarmCalendar;

//        cal.add(Calendar.SECOND, 10);
 
        //Create a new PendingIntent and add it to the AlarmManager
        Intent intent = new Intent(this, AlarmReceiverActivity.class);
        intent.putExtra("Nametask" , taskName);
        intent.putExtra("TaskDescription", taskDescription);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
            12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager am = 
            (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                pendingIntent);
	}

	private void addingTaskToDataBase() {
		Task task = new Task();
		task.setTaskName(addTaskName.getText().toString());
		task.setDescription(addTaskDescription.getText().toString());
		task.setCategory(categorySpinner.getSelectedItem().toString());
		task.setDate(setDateButton.getText().toString());
		task.setDuration(calculatingDurationOfEvents(startEve, endEve));
		task.setOnTop(checkOnTop());

		TaskHelper dataBase = new TaskHelper(CreateTaskActivity.this);
		if (dataBase.addTask(task)) {
			Toast.makeText(CreateTaskActivity.this, TASK_CREATED,
					Toast.LENGTH_SHORT);
		} else {
			Toast.makeText(CreateTaskActivity.this, TASK_NOT_CREATED,
					Toast.LENGTH_LONG);
		}
		Toast.makeText(CreateTaskActivity.this, TASK_CREATED,
				Toast.LENGTH_SHORT);
	}

	private boolean checkOnTop() {
		if (checkBoxOnTop.isChecked()) {
			return true;
		} else {
			return false;
		}
	}
}